package top.mingyi4cjh.cms.dao;

import com.alibaba.fastjson.JSON;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;
import top.mingyi4cjh.cms.dataobject.UserIdentifyDO;
import top.mingyi4cjh.cms.service.RedisService;

import javax.annotation.Resource;

import static top.mingyi4cjh.cms.common.utils.Field.ONE_DAY;

/**
 * @author MingYi
 */
@Component
public class UserIdentifyDao {

    @Resource
    private UserIdentifyDOMapper userIdentifyDOMapper;

    @Resource
    private RedisService redisService;

    public void insert(Long userId, int status) {
        UserIdentifyDO userIdentifyDO = new UserIdentifyDO();
        userIdentifyDO.setUserId(userId);
        userIdentifyDO.setIdentify(status);
        userIdentifyDOMapper.insertSelective(userIdentifyDO);
    }

    public void update(Long userId, Integer status) {
        UserIdentifyDO userIdentifyDO = new UserIdentifyDO();
        userIdentifyDO.setUserId(userId);
        userIdentifyDO.setIdentify(status);
        userIdentifyDOMapper.updateByPrimaryKeySelective(userIdentifyDO);
    }

    public int queryUserIdentify(Long userId) {
        String key = "cms:user:identify:" + userId;
        String value = (String) redisService.get(key);
        if (!StringUtils.isEmpty(value)) {
            redisService.expire(key, ONE_DAY);
            UserIdentifyDO result = JSON.parseObject(value, UserIdentifyDO.class);
            return result.getIdentify();
        }

        UserIdentifyDO result = userIdentifyDOMapper.selectByPrimaryKey(userId);
        redisService.set(key, JSON.toJSONString(value), ONE_DAY);
        return result.getIdentify();
    }
}
